package cn.tedu.pet.product.service.impl;

import cn.tedu.pet.commons.ex.ServiceException;
import cn.tedu.pet.commons.pojo.vo.PageData;
import cn.tedu.pet.product.mapper.BreedMapper;
import cn.tedu.pet.product.pojo.entity.Breed;
import cn.tedu.pet.product.pojo.param.BreedAddNewParam;
import cn.tedu.pet.product.pojo.param.BreedUpdateParam;
import cn.tedu.pet.product.pojo.vo.BreedListItemVO;
import cn.tedu.pet.product.pojo.vo.BreedStandardVO;
import cn.tedu.pet.product.pojo.vo.BreedTreeItemVO;
import cn.tedu.pet.product.service.IBreedService;
import cn.tedu.pet.commons.util.PageInfoToPageDataConverter;
import cn.tedu.pet.commons.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Slf4j
@Service
public class BreedServiceImpl implements IBreedService {

    @Autowired
    private BreedMapper breedMapper;


    @Override
    public void addNew(BreedAddNewParam breedAddNewParam) {
        log.debug("开始处理【添加类别】的业务，参数：{}", breedAddNewParam);
        // 检查相册名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Breed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", breedAddNewParam.getName());
        int countByName = breedMapper.selectCount(queryWrapper);
        log.debug("根据类别名称统计匹配的类别数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "添加类别失败，类别名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        

        // 将相册数据写入到数据库中

        Breed breed = new Breed();



        BeanUtils.copyProperties(breedAddNewParam, breed);

        int rows = breedMapper.insert(breed);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的类别数据插入到数据库，完成！");
    }


    @Override
    public void delete(Long id) {
        log.debug("开始处理[删除宠物类别数据]的业务,参数:{}",id);
        QueryWrapper<Breed> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById=breedMapper.selectCount(queryWrapper);
        log.debug("根据类别ID统计匹配的类别数量,结果:{}",countById);
        if (countById==0){
            String message="删除类别数据失败,ID不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        breedMapper.deleteById(id);

    }

    @Override
    public void updateInfoById(Long id, BreedUpdateParam breedUpdateParam) {
        log.debug("开始处理[修改类别数据]的业务,ID: {},新数据",id,breedUpdateParam);
        QueryWrapper<Breed> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById=breedMapper.selectCount(queryWrapper);
        log.debug("根据类别ID统计匹配的类别数量，结果：{}", countById);
        if (countById==0){
            String message="修改类别数据失败，类别数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Breed breed=new Breed();
        BeanUtils.copyProperties(breedUpdateParam,breed);
        breed.setId(id);
        int rows=breedMapper.updateById(breed);
        if (rows!=1){
            String message="修改类别信息失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        log.warn("将新的类别数据更新入到数据库，完成！");



    }

    @Override
    public BreedStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询类别详情】的业务，参数：{}", id);
        BreedStandardVO queryResult = breedMapper.getStandardById(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public List<BreedListItemVO> listByParentId(Long parentId) {
        log.debug("开始处理[根据父类id查询子类列表]");
        List<BreedListItemVO> list=breedMapper.listByParentId(parentId);
        return list;
    }

    @Override
    public PageData<BreedListItemVO> list(Integer pageNum) {
        Integer pageSize=5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<BreedListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[查询类别列表]的业务,页码:{},每页记录数:{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<BreedListItemVO> list=breedMapper.list();
        PageInfo<BreedListItemVO> pageInfo=new PageInfo<>(list);
        PageData<BreedListItemVO>pageData= PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}",pageData);
        return pageData;
    }


    @Override
    public List<BreedTreeItemVO> listTree() {
        log.debug("开始处理【获取类别树】的业务，参数：无");
        List<BreedTreeItemVO> breedTree = new ArrayList<>();

        List<BreedListItemVO> breedList = breedMapper.list();
        Map<Long, BreedListItemVO> allBreedMap = transformListToMap(breedList);
        for (Long key : allBreedMap.keySet()) {
            BreedListItemVO mapItem = allBreedMap.get(key);
            if (mapItem.getParentId() == 0) {
                BreedTreeItemVO breedTreeItemVO = convertListItemToTreeItem(mapItem);
                breedTree.add(breedTreeItemVO);

                fillChildren(mapItem, breedTreeItemVO, allBreedMap);
            }
        }

        return breedTree;
    }

    private Map<Long, BreedListItemVO> transformListToMap(List<BreedListItemVO> breedList) {
        Map<Long, BreedListItemVO> categoryMap = new LinkedHashMap<>();
        for (BreedListItemVO breedListItemVO : breedList) {
            if (breedListItemVO.getEnable() == 0) {
                continue;
            }
            categoryMap.put(breedListItemVO.getId(), breedListItemVO);
        }
        return categoryMap;
    }

    private void fillChildren(BreedListItemVO listItem, BreedTreeItemVO currentTreeItem, Map<Long, BreedListItemVO> allCategoryMap) {
        if (listItem.getIsParent() == 1) {
            currentTreeItem.setChildren(new ArrayList<>());
            Set<Long> keySet = allCategoryMap.keySet();
            for (Long key : keySet) {
                BreedListItemVO mapItem = allCategoryMap.get(key);
                if (mapItem.getParentId() == listItem.getId()) {
                    BreedTreeItemVO breedTreeSubItemVO = convertListItemToTreeItem(mapItem);
                    currentTreeItem.getChildren().add(breedTreeSubItemVO);
                    if (mapItem.getIsParent() == 1) {
                        fillChildren(mapItem, breedTreeSubItemVO, allCategoryMap);
                    }
                }
            }
        }
        System.out.println();
    }

    private BreedTreeItemVO convertListItemToTreeItem(BreedListItemVO listItem) {
        return new BreedTreeItemVO()
                .setValue(listItem.getId())
                .setLabel(listItem.getName());
    }

}
